﻿using System;
using System.Collections;
using System.Collections.Generic;

using IBatisNet.DataAccess;

using AUV5.Model;
using AUV5.DAL;
using AUV5.DAL.Interface;
using AUV5.DAL.Dao;
using AUV5.Common;
using System.Web;

namespace AUV5.BLL
{
    /// <summary>
    /// 功能：     UserInfo业务逻辑实现
    /// 作者：     lwl
    /// 日期：     2011/10/14
    /// 修改日期： 
    /// 修改人：
    /// 修改内容：
    /// </summary>
    public class UserInfoBLL : BaseBLL
    {
        private static UserInfoBLL instance = null;
        private static object syncRoot = new object();
        private IDaoManager daoManager = ServiceConfig.Instance.DaoManager;
        private IUserInfoDao dao = null;

        private UserInfoBLL()
        {
            dao = UserInfoSqlMapDao.Instance;
        }

        public static UserInfoBLL Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new UserInfoBLL();
                        }
                    }
                }
                return instance;
            }
        }

        #region 基本操作
        /// <summary>
        /// 得到最大行数
        /// </summary>
        /// <returns></returns>
        public int GetMaxCounts()
        {
            try
            {
                //daoManager.BeginTransaction();

                int count = dao.GetMaxCounts();

                //daoManager.CommitTransaction();

                return count;
            }
            catch
            {
                //daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 得到列表
        /// </summary>
        /// <returns></returns>
        public System.Collections.Generic.IList<UserInfo> GetList()
        {
            try
            {
                //daoManager.BeginTransaction();

                System.Collections.Generic.IList<UserInfo> list = dao.GetList();

                //daoManager.CommitTransaction();

                return list;
            }
            catch
            {
                //daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 通过不同参数得到列表
        /// </summary>
        /// <param name="TopCounts"></param>
        /// <returns></returns>
        private System.Collections.Generic.IList<UserInfo> GetListByParameters(object TopCounts, UserInfo userinfo)
        {
            try
            {
                //daoManager.BeginTransaction();

                Hashtable ht = new Hashtable();
                ht.Add("TopCounts", TopCounts);
                System.Collections.Generic.IList<UserInfo> list = dao.GetListByParameters(ht);

                //daoManager.CommitTransaction();

                return list;
            }
            catch
            {
                //daoManager.RollBackTransaction();
                throw;
            }
        }


        /// <summary>
        /// 得到明细
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public UserInfo GetDetail(System.String userid)
        {
            try
            {
                ///daoManager.BeginTransaction();
                UserInfo user = new UserInfo();
                user.UserID = userid;
                user = dao.GetDetail(user);

                //joanna 11.11.05
                if (user != null)
                {
                    //设置默认图片
                    user.PhotoPath = string.IsNullOrWhiteSpace(user.PhotoPath) ? CommonDefine.USER_DEFAULT_PHOTO : user.PhotoPath;
                    return user;
                }
                else
                    return null;

                ///daoManager.CommitTransaction();
            }
            catch
            {
                ///daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="userinfo"></param>
        /// <returns></returns>
        public int Update(UserInfo userinfo)
        {
            try
            {
                //HTML处理
                userinfo.Description = userinfo.Description.HTMLEnCode();
                userinfo.RealName = userinfo.RealName.HTMLEnCode();
                userinfo.Address = userinfo.Address.HTMLEnCode();

                ///daoManager.BeginTransaction();

                return dao.Update(userinfo);

                ///daoManager.CommitTransaction();
            }
            catch
            {
                ///daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public int Delete(System.String userid)
        {
            try
            {
                ///daoManager.BeginTransaction();

                return dao.Delete(userid);

                ///daoManager.CommitTransaction();
            }
            catch
            {
                ///daoManager.RollBackTransaction();
                throw;
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="userinfo"></param>
        /// <returns></returns>
        public int Delete(UserInfo userinfo)
        {
            try
            {
                ///daoManager.BeginTransaction();

                return dao.Delete(userinfo);

                ///daoManager.CommitTransaction();
            }
            catch
            {
                ///daoManager.RollBackTransaction();
                throw;
            }
        }
        #endregion

        #region 通过用户名获取用户信息（唯一）
        /// <summary>
        /// 通过用户名获取用户信息（唯一）
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public UserInfo GetDetailByName(System.String userName)
        {
            try
            {
                ///daoManager.BeginTransaction();
                UserInfo user = new UserInfo();
                user.UserName = userName;
                return dao.GetDetail(user);

                ///daoManager.CommitTransaction();
            }
            catch
            {
                ///daoManager.RollBackTransaction();
                throw;
            }
        }
        #endregion

        #region 通过邮箱获取用户信息（唯一）
        /// <summary>
        /// 通过邮箱获取用户信息（唯一）
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public UserInfo GetDetailByEmail(string email)
        {
            try
            {
                ///daoManager.BeginTransaction();
                UserInfo user = new UserInfo();
                user.Email = email;
                return dao.GetDetail(user);

                ///daoManager.CommitTransaction();
            }
            catch
            {
                ///daoManager.RollBackTransaction();
                throw;
            }
        }
        #endregion

        #region 用户注册State=0未激活
        /// <summary>
        /// 用户注册State=0未激活
        /// </summary>
        /// <param name="user"></param>
        /// <returns>100:成功，110：服务器错误，201：邮箱已存在，202：用户名已存在</returns>
        public string FirstStepOfRegister(UserInfo user, out string userID)
        {
            try
            {
                userID = Guid.NewGuid().ToString();
                user.UserID = userID;
                user.RoleID = BLL.RoleInfoBLL.Instance.GetRoleIDByName("visitor");
                user.State = (int)Common.Enum.auvState.Disable;
                user.IsDel = (int)Common.Enum.auvDel.NotDel;
                user.CreateDate = DateTime.Now;
                user.UpdateDate = DateTime.Now;
                user.BeginDate = DateTime.Now;
                user.EndDate = DateTime.Now;

                //用户Love9的数据监测
                HttpCookie userkey = HttpContext.Current.Request.Cookies["nwr_wmas_userkey"];
                HttpCookie cikey = HttpContext.Current.Request.Cookies["nwr_wmas_cikey"];

                user.WMAS_UK = userkey == null ? "" : userkey.Value;
                user.WMAS_CK = cikey == null ? "" : cikey.Value;


                if (GetDetailByEmail(user.Email) != null)
                {
                    return "201";
                }
                if (GetDetailByName(user.UserName) != null)
                {
                    return "202";
                }
                else
                {
                    dao.Add(user);
                    //发送激活邮件
                    SendActiveEmail(user);
                    return "100";
                }
            }
            catch
            {
                userID = string.Empty;
                return "110";
                throw;
            }

        }
        #endregion

        #region 发送激活帐户的邮件
        /// <summary>
        /// 发送激活帐户的邮件 
        /// </summary>
        /// <param name="user"></param>
        public void SendActiveEmail(UserInfo user)
        {
            //生成激活码
            ActivationCode code = new ActivationCode();
            code.ACID = Guid.NewGuid().ToString();
            code.UserID = user.UserID;
            code.Code = new Random().Next(1000, 9999).ToString();
            code.Status = (int)Common.Enum.ActivationCodeStatus.ActiveUser;
            code.CreateDate = DateTime.Now;
            code.EndDate = DateTime.Now;
            ActivationCodeBLL.Instance.Add(code);

            string subject = "AUV5（唯5网）注册帐户激活";
            System.Text.StringBuilder body = new System.Text.StringBuilder();

            body.Append(@"感谢您注册成为我们的会员，请点击以下连接激活您的账户：");
            body.AppendFormat(@"<br /><a href='{0}{1}'>点此激活</a><br />", new Common.PageBase().GetHostAddress(), "/Pages/UserActive.aspx?userid=" + user.UserID + "&key=" + GetActiveKey(user.UserID, code.Code));

            //body.Append(@"<br /><br />本邮件为测试邮件，以上链接还不能为您提供服务，各位请不要当真！！！");

            Common.MailHelper mail = new MailHelper();
            mail.SendMail(user.Email, subject, body);
        }

        //加密激活码
        private string GetActiveKey(string userid, string code)
        {
            Common.PageBase pagebase = new Common.PageBase();
            string step1 = pagebase.EncryptMD5(code);
            string step2 = pagebase.EncryptMD5(userid + step1);
            string final = step2.Substring(6, 8);
            return final;
        }
        #endregion

        #region 帐户激活 State=1
        /// <summary>
        /// 帐户激活 State=1
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public bool Activate(string userid, string key)
        {
            ActivationCode code = ActivationCodeBLL.Instance.GetCodeByUserIDAndStatus(userid, (int)Common.Enum.ActivationCodeStatus.ActiveUser);
            if (code != null)
            {
                if (key == GetActiveKey(userid, code.Code))
                {
                    code.Status = (int)Common.Enum.auvState.Disable;
                    //激活完成后
                    ActivationCodeBLL.Instance.Delete(code);
                    UserInfo user = GetDetail(userid);
                    user.State = (int)Common.Enum.auvState.Enabled;
                    return Update(user) > 0;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }

        }
        #endregion

        #region  用户登录  Add by Vinlon
        /// <summary>
        /// 用户登录，检查用户名和密码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private UserInfo Login(string userNameOrEmail, string password, bool isEmail)
        {
            UserInfo user = new UserInfo();
            if (isEmail)
            {
                user.Email = userNameOrEmail;
            }
            else
            {
                user.UserName = userNameOrEmail;
            }

            user.Password = password;
            IList list = dao.GetUserByUserInfo(user);
            if (list.Count > 0)
            {
                return list[0] as UserInfo;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 用户登录，检查Email和密码
        /// </summary>
        /// <param name="userEmail"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private UserInfo LoginByUserEmail(string userEmail, string password)
        {
            return this.Login(userEmail, password, true);
        }

        /// <summary>
        /// 用户登录，检查用户名和密码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns>返回用户实例</returns>
        public UserInfo Login(string userName, string password)
        {
            try
            {
                Model.UserInfo user = this.Login(userName, password, false);
                if (user == null)
                {
                    user = this.LoginByUserEmail(userName, password);
                }

                if (user != null)
                {
                    //无论用户是否已经激活 都更新最近登录时间
                    user.LastLogin = DateTime.Now;
                    BLL.UserInfoBLL.Instance.Update(user);

                    //设置默认图片
                    user.PhotoPath = string.IsNullOrWhiteSpace(user.PhotoPath) ? "/!images/avatar.jpg" : user.PhotoPath;
                }
                return user;
            }
            catch
            {
                return null;
                throw;
            }
        }
        #endregion

        #region##通过用户名得到用户ID
        /// <summary>
        /// 通过用户名得到用户ID
        /// 创建人：Wilson
        /// 创建时间：2011-10-27
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public string GetUserIdByUserName(string username)
        {
            try
            {
                ///daoManager.BeginTransaction();

                return dao.GetUserIdByUserName(username);

                ///daoManager.CommitTransaction();
            }
            catch
            {
                ///daoManager.RollBackTransaction();
                throw;
            }
        }
        #endregion

        #region  获取分页的用户信息
        /// <summary>
        /// 获取分页的用户信息
        /// </summary>
        /// <param name="pager"></param>
        /// <returns></returns>
        public IList<UserInfo> GetPagedList(NetPager pager)
        {
            try
            {
                return dao.GetPagedList(pager);
            }
            catch
            {

                throw;
            }
        }
        #endregion

        #region 获取用户名，若用户不存在则返回“用户不存在”
        /// <summary>
        /// 获取用户名，若用户不存在则返回“用户不存在”
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public string GetUserName(string userid)
        {
            try
            {
                UserInfo user = GetDetail(userid);
                if (user != null)
                {
                    return user.UserName;
                }
                else
                {
                    return "用户不存在";
                }

            }
            catch
            {

                throw;
            }
        }
        #endregion

        #region    发送找回密码的邮件
        /// <summary>
        /// 发送找回密码的邮件 
        /// </summary>
        /// <param name="userID"></param>
        public void SendRetrievePasswordEmail(UserInfo user)
        {
            try
            {
                Random r = new Random();
                int intCode = r.Next(1000, 9999);
                ActivationCode newCode = new ActivationCode();
                newCode.ACID = Guid.NewGuid().ToString();
                newCode.UserID = user.UserID;
                newCode.Code = intCode.ToString();
                newCode.Status = (int)Common.Enum.ActivationCodeStatus.ForgetPassword;
                newCode.CreateDate = DateTime.Now;
                newCode.EndDate = DateTime.Now;

                ActivationCodeBLL.Instance.Add(newCode);

                string finalSecret = GetRetrieveKey(user.UserID, newCode.Code);

                string host = new Common.PageBase().GetHostAddress();

                string url = host + "/Pages/Password.aspx?uid=" + user.UserID + "&s=" + finalSecret;

                string subject = "唯5网密码找回";

                string email = user.Email;

                Common.MailHelper mail = new Common.MailHelper();

                System.Text.StringBuilder body = new System.Text.StringBuilder();

                body.Append(@"尊敬的唯5网用户：<br />");
                body.Append(@"您好！<br />");
                body.Append(@"您在唯5网上申请了找回密码，请点击以下链接确认更改。<br />");
                body.Append(string.Format("<a href='{0}'>点此找回密码</a>", url));
                body.Append(@"如果上面的链接无法点击，您也可以复制以下链接到您浏览器的地址栏内，然后按“回车”键打开预设页面，完成密码的找回。<br />");
                body.Append(url + "<br />");
                //body.Append(@"如果有其他问题，请联系我们：");//加联系方式
                body.Append(@"谢谢!<br />今后请继续关注AUV5(唯5网)。");

                mail.SendMail(email, subject, body);
            }
            catch
            {

                throw;
            }
        }

        //获取找回密码的密钥
        public string GetRetrieveKey(string userID, string code)
        {
            string finalSecret = null;

            UserInfo user = UserInfoBLL.Instance.GetDetail(userID);

            if (user != null)
            {
                string name = user.UserName;
                string password = user.Password;
                string secret = new Common.PageBase().EncryptMD5(userID + name + password + code);
                //密钥：MD5字符串（用户编号+姓名+密码），从第八8位之后取6位
                finalSecret = secret.Substring(7, 6);
            }
            return finalSecret;
        }

        #endregion

        #region 验证错误登录次数是否超过五次，或向记录中添加一次错误记录
        /// <summary>
        /// 验证错误登录次数是否超过五次，或向记录中添加一次错误记录
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public int FaildLoginLog(string ip, bool update)
        {
            try
            {
                Model.FailedLogins log = FailedLoginsBLL.Instance.GetDetail(ip);
                if (log != null)   //有记录
                {
                    if (log.LastUpdate.AddMinutes(15) > DateTime.Now)   //如果未已超过等待时间 
                    {
                        if (update)    //登录失败后更新记录
                        {
                            FailedLoginsBLL.Instance.AddFailedLoginCount(ip);
                            return log.ErrorCount + 1;
                        }
                        else  //登录前
                        {
                            return log.ErrorCount;  //返回失败次数
                        }
                    }
                    else    //超过等待时间
                    {
                        if (update)//登录失败
                        {
                            FailedLoginsBLL.Instance.AddOrResetFailedLoginRecord(ip); //重置失败记录
                            return 1;
                        }
                        return 0;
                    }
                }
                else //没有记录
                {
                    if (update)   //登录失败
                    {
                        FailedLoginsBLL.Instance.AddOrResetFailedLoginRecord(ip);
                        return 1;
                    }
                    return 0;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        #region 修改注册邮箱

        /// <summary>
        /// 修改用户的注册邮箱
        /// </summary>
        /// <param name="email"></param>
        public void ChangeEmail(string userid, string email)
        {
            try
            {
                SqlMap.BeginTransaction();
                UserInfo user = GetDetail(userid);
                if (user != null)
                {
                    user.Email = email;
                    user.UpdateDate = DateTime.Now;
                    user.State = (int)Common.Enum.auvState.Disable;

                    Update(user);

                    SendActiveEmail(user);
                }
                SqlMap.CommitTransaction();
            }
            catch (Exception)
            {
                SqlMap.RollBackTransaction();
                throw;
            }
        }

        #endregion
    }
}
